import React, {PureComponent} from 'react';

class Optimization extends PureComponent {

    state = {carName: "LEXUS-LS500H"}

    updateCar = () => {
        this.setState({carName: "LEXUS-ES300H"})
        // PureComponent 行的是浅比较,以下形式不会触发比较
        /*const obj = this.state
        obj.carName = "BMW-X3"
        this.state(obj)*/
    }

    // 对比数据判断是否需要重新render组件（开发一般不用这种方式）
    // PureComponent 组件实现了对比的逻辑（进行的是浅比较）
    shouldComponentUpdate(nextProps, nextState) {
        console.log(this.state, this.props);
        console.log(nextState, nextProps);
        return this.state.carName !== nextState.carName;
    }

    render() {
        const {carName} = this.state;
        return (
            <div>
                <h3>This is Optimization Component</h3>
                <span>carName:{carName}</span>
                <button onClick={this.updateCar}>OnClick</button>
                <Child carName={carName}/>
            </div>
        );
    }
}

class Child extends PureComponent {

    render() {
        return (
            <div>
                <h3>This is Child Component</h3>
                <span>for Parent carName: {this.props.carName}</span>
            </div>
        );
    }
}

export default Optimization;